<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="景点名称" prop="spotName">
        <el-input v-model="queryParams.spotName" placeholder="请输入景点名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="所属地区" prop="areaId">
        <el-select v-model="queryParams.areaId" placeholder="请选择所属地区" clearable>
          <el-option v-for="item in areaOptions" :key="item.areaId" :label="item.areaName" :value="item.areaId" />
        </el-select>
      </el-form-item>
      <el-form-item label="景点地址" prop="address">
        <el-input v-model="queryParams.address" placeholder="请输入景点地址" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="开放时间" prop="openTime">
        <el-input v-model="queryParams.openTime" placeholder="请输入开放时间" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="门票价格" prop="ticketPrice">
        <el-input v-model="queryParams.ticketPrice" placeholder="请输入门票价格" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['app:spot:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['app:spot:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['app:spot:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['app:spot:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="spotList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="景点ID" align="center" prop="spotId" />
      <el-table-column label="景点名称" align="center" prop="spotName" />
      <el-table-column label="所属地区ID" align="center" prop="areaId" />
      <el-table-column label="景点描述" align="center" prop="description" />
      <el-table-column label="景点地址" align="center" prop="address" />
      <el-table-column label="开放时间" align="center" prop="openTime" />
      <el-table-column label="门票价格" align="center" prop="ticketPrice" />
      <el-table-column label="景点图片" align="center" prop="image">
        <template slot-scope="scope">
          <el-image style="width: 100px; height: 100px" :src="scope.row.image" :preview-src-list="[scope.row.image]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['app:spot:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['app:spot:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改景点对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="景点名称" prop="spotName">
          <el-input v-model="form.spotName" placeholder="请输入景点名称" />
        </el-form-item>
        <el-form-item label="所属地区" prop="areaId">
          <el-select v-model="form.areaId" placeholder="请选择所属地区">
            <el-option v-for="item in areaOptions" :key="item.areaId" :label="item.areaName" :value="item.areaId" />
          </el-select>
        </el-form-item>
        <el-form-item label="景点描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="景点地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入景点地址" />
        </el-form-item>
        <el-form-item label="开放时间" prop="openTime">
          <el-input v-model="form.openTime" placeholder="请输入开放时间" />
        </el-form-item>
        <el-form-item label="门票价格" prop="ticketPrice">
          <el-input v-model="form.ticketPrice" placeholder="请输入门票价格" />
        </el-form-item>
        <el-form-item label="景点图片" prop="image">
          <el-upload class="avatar-uploader" :action="upload.url" :headers="upload.headers" :show-file-list="false"
            :on-success="handleImageSuccess" :before-upload="beforeImageUpload">
            <img v-if="form.image" :src="form.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSpot, getSpot, delSpot, addSpot, updateSpot } from "@/api/app/spot"
import { listArea } from "@/api/app/area"
import { getToken } from "@/utils/auth"

export default {
  name: "Spot",
  data () {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 景点表格数据
      spotList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        spotName: null,
        areaId: null,
        description: null,
        address: null,
        openTime: null,
        ticketPrice: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        spotName: [
          { required: true, message: "景点名称不能为空", trigger: "blur" }
        ],
        areaId: [
          { required: true, message: "所属地区ID不能为空", trigger: "blur" }
        ],
        image: [
          { required: true, message: "请上传景点图片", trigger: "blur" }
        ],
      },
      // 添加地区列表数据
      areaOptions: [],
      // 添加上传相关配置
      upload: {
        // 图片上传地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() }
      },
    }
  },
  created () {
    //打印process.env.VUE_APP_BASE_API
    this.getList()
    this.getAreaList()
  },
  methods: {
    /** 查询景点列表 */
    getList () {
      this.loading = true
      listSpot(this.queryParams).then(response => {
        this.spotList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取地区下拉框数据 */
    getAreaList () {
      listArea().then(response => {
        this.areaOptions = response.rows
      })
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset () {
      this.form = {
        spotId: null,
        spotName: null,
        areaId: null,
        description: null,
        address: null,
        openTime: null,
        ticketPrice: null,
        image: null,
        createTime: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.spotId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset()
      this.open = true
      this.title = "添加景点"
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset()
      const spotId = row.spotId || this.ids
      getSpot(spotId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改景点"
      })
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.spotId != null) {
            updateSpot(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addSpot(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const spotIds = row.spotId || this.ids
      this.$modal.confirm('是否确认删除景点编号为"' + spotIds + '"的数据项？').then(function () {
        return delSpot(spotIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('app/spot/export', {
        ...this.queryParams
      }, `spot_${new Date().getTime()}.xlsx`)
    },
    // 修改图片上传成功的处理方法
    handleImageSuccess (res, file) {
      console.log(res)
      console.log(file)
      if (res.code === 200) {

        this.form.image = process.env.VUE_APP_BASE_API + res.fileName
        this.$modal.msgSuccess("上传成功")
      } else {
        this.$modal.msgError("上传失败")
      }
    },
    beforeImageUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return false
      }
      return true
    },
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
